package maosui.websocket;

import net.sf.json.JSONObject;
import org.hibernate.*;

import javax.websocket.*;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.sql.Timestamp;
import java.util.*;


@ServerEndpoint("/live")
public class Live extends LiveWebSocket {

    public void init(Live client, JSONObject data){
        sendEventMessage("init_success", new Date().getTime());
    }

    public void getOnline(Live client, JSONObject data){
        DBManager.getSession();
        if(DBManager.session != null && DBManager.session.isConnected()){
            List<Integer> list = getOnlineSeekerIds();
            if(list != null){
                if(list.size() > 0)
                {
                    sendEventMessage("queue",  DBManager.session.createSQLQuery("SELECT userid,username,useremail,usertype,lastlogintime FROM 51lpz_users WHERE userid IN(:ids)")
                            .setParameterList("ids", list).list());
                    DBManager.closeSession();
                }
            }
        }else{
            sendEventMessage("queue",  null);
        }
    }


    @OnOpen
    public void onOpen(Session session){
        long s = System.currentTimeMillis();
        super.start(session);
        if(user != null && user.getUserType() == UserType.COMPANY){
            org.hibernate.Session dbSession = DBManager.getSession();
            Transaction tx = dbSession.beginTransaction();
            room.setUpdateTime(new Timestamp(new Date().getTime()));
            dbSession.saveOrUpdate(room);
            tx.commit();
            dbSession.close();

            getOnline(this, null);
        }
        System.err.println("open time : " + (System.currentTimeMillis() - s));
    }

    @OnMessage
    public void onMessage(String message){
        long s = System.currentTimeMillis();
        super.incoming(message);
        System.err.println("执行耗时: " + (System.currentTimeMillis() - s));
    }

    @OnClose
    public void onClose(){
        super.end();
        if(user != null && user.getUserType() == UserType.COMPANY){
            Transaction tx = DBManager.getSession().beginTransaction();
            //room.setOnline((byte) 0);
            room.setUpdateTime(new Timestamp(new Date().getTime()));
            DBManager.session.saveOrUpdate(room);
            tx.commit();
            DBManager.closeSession();
        }else if (user != null && user.getUserType() == UserType.SEEKER){
            List<LiveWebSocket> lives = getOnlineSeekers();
            int queueIndex = 1;
            for (LiveWebSocket live : lives) {
                live.sendEventMessage("queue", queueIndex);
                queueIndex++;
            }
        }
        //close();
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        System.err.println("Chat Error: " + t.toString());t.printStackTrace();
    }



    public void __broadcastToUser(Live client, JSONObject m){
        _system_eventToUser(m, "broadcast");
    }

    public void __eventToUser(Live client, JSONObject m){
        _system_eventToUser(m, m.getString("event_type"));
    }

    protected void _system_eventToUser(JSONObject m, String event){
        int uid;
        try{
            uid = m.getInt("toUid");
            if(uid == 0)uid = this.room.getUid();
        }catch (Exception e){
            uid = this.room.getUid();
            e.printStackTrace();
        }
        if(uid > 0){
            Live live = (Live) getClientByUid(uid);
            if(live != null){
                //live.sendEventMessage(event == null ? m.getString("event_type") : event, m.getJSONObject("event_data"));
                System.out.println(event + " to " + uid);
                live.sendEventMessage(event, m.get("event_data"));
            }
        }
    }

}
